<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>getSnapshotBeforeUpdate举例</title>
  <style>
    .list {
      height: 150px;
      width: 200px;
      background-color: skyblue;
      overflow: auto;
    }

    .news {
      height: 30px;
    }
  </style>
</head>

<body>
  <!-- 准备一个容器 -->
  <div id="root"></div>
  <!--  引入React核心库-->
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <!--  引入react-dom,用于支持React操作Dom-->
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <!-- 引入babel，用于将jsx转为js-->
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script src="https://unpkg.com/prop-types@15.6.2/prop-types.js"></script>

  <script type="text/babel">
    // 1.创建一个组件
    class NewList extends React.Component {// render调用时机：初始化渲染，状态更新之后
      state = {
        newsArr: []
      }
      getSnapshotBeforeUpdate() {
        console.log(this.refs.list.scrollHeight);
        // list 内容区的高度
        return this.refs.list.scrollHeight
      }
      componentDidUpdate(preProps, preState, height) {
        console.log('componentDidUpdate');
        // 向上窜的高度
        this.refs.list.scrollTop += this.refs.list.scrollHeight - height
      }
      componentDidMount() {
        setInterval(() => {
          // 获取状态
          const { newsArr } = this.state
          // 模拟一条新闻
          const news = '新闻' + (newsArr.length + 1)
          // 更新状态
          this.setState({ newsArr: [news, ...newsArr] })
        }, 1000)
      }
      render() {
        console.log('render--组件渲染');
        return (
          <div className="list" ref='list'>
            {
              this.state.newsArr.map((item, index) => {
                return <div className="news" key={index}>{item}</div>
              })
            }
          </div>
        )
      }
    }
    // 2.渲染组件到页面
    const container = document.getElementById('root')
    const root = ReactDOM.createRoot(container)
    root.render(<NewList />)
  </script>
</body>

</html>